import { useRef, useState, useEffect } from 'react';
import './Canvas.css';
import { Button, Modal, Slider, Switch, ColorPicker, Space, Divider, Typography } from 'antd';
// import { useNavigate } from 'react-router-dom'; // 已不使用
import SimpleModelViewer from '../../compages/DigitalHuman';
import ChatIcon from '../../compages/ChatIcom/Index';
import { useSelector, useDispatch } from 'react-redux';
import type { RootState } from '../../store';
import { addDanmu, type DanmuItem } from '../../store/slices/danmuSlice';
import { setLang } from '../../store/slices/appSlice';
import EmojiPicker from 'emoji-picker-react';
import { hasRole, ROLES } from '../../utils/auth';
import AIChatWithAnimation from '../../compages/AIChatWithAnimation';

console.log('CanvasPage 渲染', Date.now());
console.log('SimpleModelViewer 渲染', Date.now());
console.log('AppRouter 渲染', Date.now());
console.log('main.tsx 渲染', Date.now());

// 扩展弹幕颜色选项
const danmuColors = [
  '#ff4d4f', '#40a9ff', '#36cfc9', '#fadb14', '#9254de', '#ff7a45', '#73d13d',
  '#ff7875', '#69c0ff', '#5cdbd3', '#fff566', '#b37feb', '#ff9c6e', '#95de64',
  '#ff4d4f', '#1890ff', '#13c2c2', '#faad14', '#722ed1', '#fa541c', '#52c41a'
];

// 预设弹幕样式
const danmuStyles = [
  { name: '默认', value: 'default', color: '#40a9ff', fontSize: 20 },
  { name: '醒目', value: 'highlight', color: '#ff4d4f', fontSize: 24 },
  { name: '优雅', value: 'elegant', color: '#9254de', fontSize: 18 },
  { name: '活力', value: 'vibrant', color: '#fadb14', fontSize: 22 },
  { name: '清新', value: 'fresh', color: '#36cfc9', fontSize: 19 },
];

const SENSITIVE_WORDS = ['傻逼', 'sb', 'fuck', '草', '操', '死', '妈的', 'shit', 'bitch', 'nmsl'];



// 定义一个函数，用于过滤敏感词
function filterSensitiveWords(text: string) {
  // 初始化结果为输入的文本
  let result = text;
  // 遍历敏感词数组
  SENSITIVE_WORDS.forEach(word => {
    // 定义正则表达式，用于匹配敏感词
    const reg = new RegExp(word, 'gi');
    // 将敏感词替换为*，长度与敏感词相同
    result = result.replace(reg, '*'.repeat(word.length));
  });
  // 返回替换后的结果
  return result;
}

// 服装选项，可扩展
const clothingOptions = [
  {
    id: 1,
    label: '服装A',
    value: '/models/girl.glb',
  },
  {
    id: 2,
    label: '服装B',
    value: '/models/danceGirl.glb',
  },
  // 可继续添加更多服装
];

function Index() {
  // 创建一个引用，用于获取页面中的box元素
  const boxRef = useRef<HTMLDivElement>(null);
  // 创建一个状态，用于存储当前主题色
  const [isDay, setIsDay] = useState(true);
  // 创建一个状态，用于存储当前动画状态
  const [animation, setAnimation] = useState('idle');
  // 创建一个状态，用于存储是否显示图表
  const [showChart, setShowChart] = useState(false);
  // 创建一个状态，用于存储聊天消息
  const [chatMessages, setChatMessages] = useState<{from: 'user'|'ai', text: string, isVoice?: boolean}[]>([]);
  // 创建一个状态，用于存储聊天输入框的内容
  const [chatInput, setChatInput] = useState('');
  // 创建一个状态，用于存储是否正在加载聊天回复
  const [chatLoading, setChatLoading] = useState(false);
  // 从Redux中获取弹幕列表
  const danmuList = useSelector((state: RootState) => state.danmu.list);
  // 获取Redux的dispatch方法
  const dispatch = useDispatch();
  // 创建一个状态，用于存储弹幕输入框的内容
  const [danmuInput, setDanmuInput] = useState('');
  // 创建一个状态，用于存储是否显示弹幕输入框
  const [showDanmuInput, setShowDanmuInput] = useState(false);
  // 创建一个状态，用于存储是否显示表情选择器
  const [showEmoji, setShowEmoji] = useState(false);
  // 创建一个状态，用于存储是否显示弹幕
  const [showDanmu, setShowDanmu] = useState(false);
  // 创建一个引用，用于存储弹幕的id
  const danmuId = useRef(0);
  // 获取路由的navigate方法
  // const navigate = useNavigate(); // 已不使用
  // 从Redux中获取当前语言
  const lang = useSelector((state: RootState) => state.app.lang);
  // 创建一个状态，用于存储是否显示弹幕设置
  const [danmuSettingsVisible, setDanmuSettingsVisible] = useState(false);
  // 创建一个状态，用于存储是否启用弹幕
  const [danmuEnabled, setDanmuEnabled] = useState(true);
  // 创建一个状态，用于存储弹幕速度
  const [danmuSpeed, setDanmuSpeed] = useState(1.5); // 1-5
  // 创建一个状态，用于存储弹幕字体大小
  const [danmuFontSize, setDanmuFontSize] = useState(20); // px
  // 创建一个状态，用于存储视频是否正在播放
  const [isVideoPlaying, setIsVideoPlaying] = useState(true);
  // 创建一个状态，用于存储当前服装模型路径
  const [modelPath] = useState(clothingOptions[0].value); // setModelPath未用
  // 判断当前用户是否为管理员
  const isAdmin = hasRole(ROLES.ADMIN);
  // const [recognizing, setRecognizing] = useState(false); // 已不使用
  const [showAIChat, setShowAIChat] = useState(false);

  // 新增弹幕相关状态
  const [selectedDanmuColor, setSelectedDanmuColor] = useState('#40a9ff');
  const [selectedDanmuStyle, setSelectedDanmuStyle] = useState('default');
  const [danmuOpacity, setDanmuOpacity] = useState(1);
  const [danmuShadow, setDanmuShadow] = useState(true);
  const [danmuBold, setDanmuBold] = useState(false);
  const [danmuItalic, setDanmuItalic] = useState(false);
  const [danmuStroke, setDanmuStroke] = useState(true);
  const [danmuTimeOffset, setDanmuTimeOffset] = useState(0); // 弹幕时间偏移（秒）
  
  // 视频时间相关状态
  const [currentVideoTime, setCurrentVideoTime] = useState(0);
  const videoRef = useRef<HTMLVideoElement>(null);

  // 页面加载时初始化主题色
  useEffect(() => {
    const savedIsDay = localStorage.getItem('isDay');
    if (savedIsDay !== null) {
      setIsDay(JSON.parse(savedIsDay));
    }
  }, []);

  // 监听 isDay，自动设置背景图片
  useEffect(() => {
    if (boxRef.current) {
      if (isDay) {
        boxRef.current.style.background = "url('/imgs/bg-day.png')";
      } else {
        boxRef.current.style.background = "url('/imgs/indexLightBackground.png')";
      }
      boxRef.current.style.backgroundSize = '100% 100%';
      boxRef.current.style.backgroundRepeat = 'no-repeat';
    }
  }, [isDay]);

  const sendChatMessage = async () => {
    if (!chatInput.trim()) return;
    setChatMessages(h => [...h, {from: 'user', text: chatInput}]);
    setChatLoading(true);
    // Mock AI回复
    setTimeout(() => {
      const mockReplies = [
        (input: string) => `我理解你说的"${input}"，这很有趣！`,
        (input: string) => `关于"${input}"，我想说的是...`,
        (input: string) => `你说得对，"${input}"确实很重要。`,
        (input: string) => `我听到了"${input}"，让我想想...`,
        (input: string) => `"${input}"这个话题很有意思呢！`,
      ];
      const reply = mockReplies[Math.floor(Math.random() * mockReplies.length)](chatInput);
      setChatMessages(h => [...h, {from: 'ai', text: reply}]);
      setAnimation('speaking');
      if ('speechSynthesis' in window) {
        const utter = new window.SpeechSynthesisUtterance(reply);
        utter.lang = 'zh-CN';
        utter.onend = () => setAnimation('idle');
        utter.onerror = () => setAnimation('idle');
        window.speechSynthesis.speak(utter);
      } else {
        setTimeout(() => setAnimation('idle'), Math.max(2000, reply.length * 120));
      }
      setChatLoading(false);
      setChatInput('');
    }, 1000);
  };

  const sendDanmu = () => {
    if (!danmuInput.trim()) return;
    const filteredText = filterSensitiveWords(danmuInput);
    
    // 根据选择的样式获取颜色和字体大小
    let finalColor = selectedDanmuColor;
    let finalFontSize = danmuFontSize;
    
    if (selectedDanmuStyle !== 'default') {
      const style = danmuStyles.find(s => s.value === selectedDanmuStyle);
      if (style) {
        finalColor = style.color;
        finalFontSize = style.fontSize;
      }
    }
    
    const newDanmu = { 
      text: filteredText, 
      id: danmuId.current++, 
      color: finalColor,
      fontSize: finalFontSize,
      opacity: danmuOpacity,
      shadow: danmuShadow,
      bold: danmuBold,
      italic: danmuItalic,
      stroke: danmuStroke,
      style: selectedDanmuStyle,
      timestamp: currentVideoTime + danmuTimeOffset // 记录发送时的视频时间加上偏移
    };
    
    console.log('发送弹幕:', newDanmu, '时间:', currentVideoTime);
    dispatch(addDanmu(newDanmu));
    setDanmuInput('');
    setShowDanmuInput(false);
  };

  const toggleLang = () => {
    const newLang = lang === 'zh' ? 'en' : 'zh';
    dispatch(setLang(newLang));
    localStorage.setItem('lang', newLang);
  };

  // 页面加载时初始化语言
  useEffect(() => {
    const savedLang = localStorage.getItem('lang');
    if (savedLang === 'zh' || savedLang === 'en') {
      dispatch(setLang(savedLang));
    }
  }, [dispatch]);

  // 获取弹幕样式
  const getDanmuStyle = (item: DanmuItem) => {
    const baseStyle = {
      color: item.color || selectedDanmuColor,
      fontSize: item.fontSize || danmuFontSize,
      opacity: item.opacity !== undefined ? item.opacity : danmuOpacity,
      fontWeight: item.bold ? 'bold' : 'normal',
      fontStyle: item.italic ? 'italic' : 'normal',
      textShadow: item.shadow !== false ? 
        `1px 1px 2px #000, 0 0 4px ${item.color || selectedDanmuColor}` : 'none',
      WebkitTextStroke: item.stroke !== false ? '1px #000' : 'none',
      animation: `danmu-move ${6 / danmuSpeed}s linear forwards`,
      animationPlayState: isVideoPlaying ? 'running' : 'paused',
    };
    
    return baseStyle;
  };

  // 获取弹幕CSS类名
  const getDanmuClassName = (item: DanmuItem) => {
    const style = danmuStyles.find(s => s.value === item.style);
    return style ? `danmu-item ${style.value}` : 'danmu-item';
  };

  // 快速颜色选择
  const handleQuickColorSelect = (color: string) => {
    setSelectedDanmuColor(color);
  };

  // 快速样式选择
  const handleQuickStyleSelect = (styleValue: string) => {
    setSelectedDanmuStyle(styleValue);
    const style = danmuStyles.find(s => s.value === styleValue);
    if (style) {
      setSelectedDanmuColor(style.color);
      setDanmuFontSize(style.fontSize);
    }
  };

  // 视频时间监听
  useEffect(() => {
    const video = videoRef.current;
    if (!video) return;

    const handleTimeUpdate = () => {
      setCurrentVideoTime(video.currentTime);
    };

    const handleLoadedMetadata = () => {
      // 视频元数据加载完成
      console.log('视频时长:', video.duration);
    };

    video.addEventListener('timeupdate', handleTimeUpdate);
    video.addEventListener('loadedmetadata', handleLoadedMetadata);

    return () => {
      video.removeEventListener('timeupdate', handleTimeUpdate);
      video.removeEventListener('loadedmetadata', handleLoadedMetadata);
    };
  }, []);

  // 清理已完成的弹幕
  useEffect(() => {
    const timer = setInterval(() => {
      // 限制弹幕数量，防止内存泄漏
      if (danmuList.length > 50) {
        // 这里可以添加清理逻辑，但由于Redux的限制，我们暂时保留所有弹幕
        // 实际项目中可以考虑添加清理action
        console.log('弹幕数量过多，建议清理');
      }
    }, 10000);

    return () => clearInterval(timer);
  }, [danmuList]);


  return (
    <div style={{ background: '#fff', minHeight: '100vh' }}>
      {/* AI语音输入聊天按钮 */}
      <button
        style={{
          position: 'fixed',
          right: 32,
          bottom: 32,
          zIndex: 2000,
          borderRadius: '50%',
          background: '#3a8bff',
          color: '#fff',
          border: 'none',
          fontSize: 28,
          width: 64,
          height: 64,
          boxShadow: '0 4px 16px rgba(58,139,255,0.18)',
          cursor: 'pointer',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
        }}
        onClick={() => setShowAIChat(true)}
        title="AI语音聊天"
      >
        🎤
      </button>
      {/* AI语音聊天弹窗 */}
      {showAIChat && (
        <div
          style={{
            position: 'fixed',
            left: 0,
            top: 0,
            width: '100vw',
            height: '100vh',
            background: 'rgba(0,0,0,0.18)',
            zIndex: 2100,
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
          }}
          onClick={() => setShowAIChat(false)}
        >
          <div
            style={{
              background: '#fff',
              borderRadius: 18,
              padding: 0,
              width: 380,
              minHeight: 420,
              boxShadow: '0 8px 32px rgba(0,0,0,0.15)',
              display: 'flex',
              flexDirection: 'column',
              position: 'relative',
              overflow: 'hidden',
            }}
            onClick={e => e.stopPropagation()}
          >
            <AIChatWithAnimation setAnimation={setAnimation} lang={lang === 'zh' ? 'zh' : 'en'} />
            <button
              style={{ position: 'absolute', top: 12, right: 16, background: 'transparent', border: 'none', fontSize: 22, color: '#888', cursor: 'pointer', zIndex: 10 }}
              onClick={() => setShowAIChat(false)}
              title="关闭"
            >×</button>
          </div>
        </div>
      )}
      <div className="box" ref={boxRef}>
        <div className="header">
          <div>
            {isAdmin && (
              <>
                <Button onClick={toggleLang} style={{ marginLeft: 8 }}>
                  {lang === 'zh' ? 'English' : '中文'}
                </Button>
                <Button onClick={() => setDanmuSettingsVisible(true)} style={{ marginLeft: 8 }}>
                  {lang === 'zh' ? '弹幕设置' : 'Danmu Settings'}
                </Button>
              </>
            )}
          </div>
        </div>
        <div className="left">
          <div className="canvas-avatar-wrap">
            <SimpleModelViewer 
              modelPath={modelPath} 
              scale={2.3} 
              position={[0, -2.4, 0]} 
              animationName={animation}
              onAnimationChange={setAnimation}
              lang={lang}
            />
          </div>
        </div>
        <div className="right" style={{ position: 'absolute', right: '3%', top: '24%', width: '65%', height: '75%', background: "url('/imgs/border-day.png')", backgroundSize: '100% 100%', backgroundRepeat: 'no-repeat', overflow: 'visible' }}>
          <div style={{ position: 'relative', width: '100%', height: '100%' }}>
            <video
              ref={videoRef}
              src="/4.mp4"
              controls
              autoPlay
              className="canvas-video"
              onError={(e) => {
                console.error('视频加载失败:', e);
                e.currentTarget.src = 'https://www.w3schools.com/html/mov_bbb.mp4';
              }}
              onPlay={() => setIsVideoPlaying(true)}
              onPause={() => setIsVideoPlaying(false)}
            />
            {showDanmu && danmuEnabled && (
              <div
                className="danmu-container"
                style={{
                  position: 'absolute',
                  left: '6%',
                  top: '10%',
                  width: '88%',
                  height: '78%',
                  pointerEvents: 'none',
                  overflow: 'hidden',
                  zIndex: 10,
                }}
              >
                {danmuList
                  .filter(item => {
                    // 只显示当前时间附近的弹幕（前后2秒范围内）
                    if (!item.timestamp) return true; // 兼容旧数据
                    const timeDiff = Math.abs(currentVideoTime - item.timestamp);
                    return timeDiff <= 2; // 2秒内的弹幕
                  })
                  .map((item, idx) => (
                    <div
                      className={getDanmuClassName(item)}
                      key={item.id}
                      style={{
                        top: `${10 + (idx % 4) * 22}px`,
                        position: 'absolute',
                        whiteSpace: 'nowrap',
                        ...getDanmuStyle(item),
                      }}
                    >
                      {item.text}
                    </div>
                  ))}
              </div>
            )}
            {showDanmuInput && (
              <div
                className="danmu-input-container"
                style={{
                  position: 'absolute',
                  bottom: 70,
                  left: 'calc(50% + 100px)',
                  transform: 'translateX(-50%)',
                  zIndex: 20,
                  display: 'flex',
                  flexDirection: 'column',
                  alignItems: 'center',
                  minWidth: '300px',
                }}
                onClick={e => e.stopPropagation()}
              >
                {/* 快速样式选择 */}
                <div style={{ marginBottom: 8, display: 'flex', gap: 4 }}>
                  {danmuStyles.map(style => (
                    <button
                      key={style.value}
                      className={`danmu-style-btn ${selectedDanmuStyle === style.value ? 'active' : ''}`}
                      onClick={() => handleQuickStyleSelect(style.value)}
                      style={{
                        color: style.color,
                        borderColor: style.color,
                        fontWeight: 'bold'
                      }}
                    >
                      {style.name}
                    </button>
                  ))}
                </div>

                {/* 快速颜色选择 */}
                <div style={{ marginBottom: 8, display: 'flex', gap: 4 }}>
                  {danmuColors.slice(0, 6).map(color => (
                    <div
                      key={color}
                      className={`danmu-color-dot ${selectedDanmuColor === color ? 'selected' : ''}`}
                      style={{
                        backgroundColor: color,
                      }}
                      onClick={() => handleQuickColorSelect(color)}
                      title={color}
                    />
                  ))}
                </div>

                {/* 时间偏移设置 */}
                <div style={{ marginBottom: 8, display: 'flex', alignItems: 'center', gap: 8 }}>
                  <span style={{ color: '#fff', fontSize: '12px' }}>时间偏移:</span>
                  <input
                    type="number"
                    value={danmuTimeOffset}
                    onChange={(e) => setDanmuTimeOffset(Number(e.target.value))}
                    style={{
                      width: '60px',
                      padding: '2px 4px',
                      borderRadius: '4px',
                      border: '1px solid #ccc',
                      fontSize: '12px'
                    }}
                    step="0.5"
                    min="-10"
                    max="10"
                  />
                  <span style={{ color: '#fff', fontSize: '12px' }}>秒</span>
                </div>

                {/* 输入框区域 */}
                <div style={{ position: 'relative', display: 'flex', alignItems: 'center', width: '100%' }}>
                  <input
                    type="text"
                    value={danmuInput}
                    onChange={e => setDanmuInput(e.target.value)}
                    placeholder="输入弹幕..."
                    style={{
                      borderRadius: 8,
                      border: 'none',
                      padding: '8px 12px',
                      fontSize: 15,
                      outline: 'none',
                      marginRight: 8,
                      flex: 1,
                      background: 'rgba(255,255,255,0.9)',
                    }}
                    onKeyDown={e => { if (e.key === 'Enter') sendDanmu(); }}
                    autoFocus
                  />
                  <button
                    className="danmu-send-btn"
                    style={{ marginLeft: 0, padding: '8px 12px' }}
                    type="button"
                    onClick={() => setShowEmoji(v => !v)}
                  >😊</button>
                  {showEmoji && (
                    <div style={{ position: 'absolute', bottom: 50, left: 0, zIndex: 100 }}>
                      <EmojiPicker
                        onEmojiClick={e => {
                          setDanmuInput(danmuInput + e.emoji);
                          setShowEmoji(false);
                        }}
                        height={350}
                      />
                    </div>
                  )}
                </div>

                {/* 预览效果 */}
                <div style={{ 
                  marginTop: 8, 
                  padding: '4px 8px', 
                  background: 'rgba(255,255,255,0.1)', 
                  borderRadius: 6,
                  fontSize: 12,
                  color: selectedDanmuColor,
                  fontWeight: danmuBold ? 'bold' : 'normal',
                  fontStyle: danmuItalic ? 'italic' : 'normal',
                  textShadow: danmuShadow ? `1px 1px 2px #000` : 'none',
                }}>
                  {danmuInput || '弹幕预览'}
                </div>

                {/* 操作按钮 */}
                <div style={{ marginTop: 8, display: 'flex', gap: 8 }}>
                  <button
                    className="danmu-send-btn"
                    onClick={sendDanmu}
                    style={{ padding: '6px 16px' }}
                  >发送</button>
                  <button
                    className="danmu-send-btn"
                    style={{ padding: '6px 16px', background: '#aaa' }}
                    onClick={() => setShowDanmuInput(false)}
                  >关闭</button>
                </div>
              </div>
            )}
            <div
              style={{
                position: 'absolute',
                right: '6%',
                bottom: '16%',
                zIndex: 30,
                display: 'flex',
                flexDirection: 'column',
                alignItems: 'flex-end',
                gap: 10
              }}
            >
              {/* 时间显示 */}
              <div
                style={{
                  background: 'rgba(0,0,0,0.7)',
                  color: '#fff',
                  padding: '4px 8px',
                  borderRadius: '4px',
                  fontSize: '12px',
                  fontFamily: 'monospace'
                }}
              >
                {Math.floor(currentVideoTime / 60)}:{(currentVideoTime % 60).toFixed(1).padStart(4, '0')}
              </div>
              <button
                className="danmu-send-btn"
                style={{ borderRadius: '50%', width: 40, height: 40, fontSize: 18, padding: 0, background: showDanmu ? '#1e90ff' : '#aaa' }}
                title={showDanmu ? (lang === 'zh' ? '隐藏弹幕' : 'Hide Danmu') : (lang === 'zh' ? '显示弹幕' : 'Show Danmu')}
                onClick={e => { e.stopPropagation(); setShowDanmu(v => !v); }}
              >
                {lang === 'zh' ? '弹' : 'Danmu'}
              </button>
              <button
                className="danmu-send-btn"
                style={{ borderRadius: '50%', width: 40, height: 40, fontSize: 18, padding: 0 }}
                title="发送弹幕"
                onClick={e => { e.stopPropagation(); setShowDanmuInput(true); }}
              >+</button>
            </div>
            <Modal
              open={danmuSettingsVisible}
              title={lang === 'zh' ? '弹幕设置' : 'Danmu Settings'}
              onCancel={() => setDanmuSettingsVisible(false)}
              footer={null}
              width={600}
            >
              <div style={{ marginBottom: 20 }}>
                <Typography.Title level={5}>{lang === 'zh' ? '基础设置' : 'Basic Settings'}</Typography.Title>
                <div style={{ marginBottom: 16 }}>
                  <span style={{ marginRight: 8 }}>{lang === 'zh' ? '弹幕开关' : 'Enable Danmu'}</span>
                  <Switch checked={danmuEnabled} onChange={setDanmuEnabled} />
                </div>
                <div style={{ marginBottom: 16 }}>
                  <span style={{ marginRight: 8 }}>{lang === 'zh' ? '弹幕速度' : 'Speed'}</span>
                  <Slider min={0.5} max={5} step={0.1} value={danmuSpeed} onChange={setDanmuSpeed} style={{ width: 200, display: 'inline-block' }} />
                  <span style={{ marginLeft: 8 }}>{danmuSpeed.toFixed(1)}x</span>
                </div>
                <div style={{ marginBottom: 16 }}>
                  <span style={{ marginRight: 8 }}>{lang === 'zh' ? '字体大小' : 'Font Size'}</span>
                  <Slider min={12} max={48} step={1} value={danmuFontSize} onChange={setDanmuFontSize} style={{ width: 200, display: 'inline-block' }} />
                  <span style={{ marginLeft: 8 }}>{danmuFontSize}px</span>
                </div>
                <div style={{ marginBottom: 16 }}>
                  <span style={{ marginRight: 8 }}>{lang === 'zh' ? '透明度' : 'Opacity'}</span>
                  <Slider min={0.1} max={1} step={0.1} value={danmuOpacity} onChange={setDanmuOpacity} style={{ width: 200, display: 'inline-block' }} />
                  <span style={{ marginLeft: 8 }}>{danmuOpacity.toFixed(1)}</span>
                </div>
              </div>

              <Divider />

              <div style={{ marginBottom: 20 }}>
                <Typography.Title level={5}>{lang === 'zh' ? '样式预设' : 'Style Presets'}</Typography.Title>
                <Space wrap>
                  {danmuStyles.map(style => (
                    <Button
                      key={style.value}
                      type={selectedDanmuStyle === style.value ? 'primary' : 'default'}
                      size="small"
                      onClick={() => handleQuickStyleSelect(style.value)}
                      style={{
                        color: style.color,
                        borderColor: style.color,
                        fontWeight: 'bold'
                      }}
                    >
                      {style.name}
                    </Button>
                  ))}
                </Space>
              </div>

              <Divider />

              <div style={{ marginBottom: 20 }}>
                <Typography.Title level={5}>{lang === 'zh' ? '颜色选择' : 'Color Selection'}</Typography.Title>
                <div style={{ marginBottom: 16 }}>
                  <span style={{ marginRight: 8 }}>{lang === 'zh' ? '自定义颜色' : 'Custom Color'}</span>
                  <ColorPicker value={selectedDanmuColor} onChange={(color) => setSelectedDanmuColor(color?.toHexString() || '#40a9ff')} />
                </div>
                <div style={{ marginBottom: 16 }}>
                  <span style={{ marginRight: 8 }}>{lang === 'zh' ? '快速选择' : 'Quick Select'}</span>
                  <Space wrap>
                    {danmuColors.slice(0, 8).map(color => (
                      <div
                        key={color}
                        style={{
                          width: 24,
                          height: 24,
                          borderRadius: '50%',
                          backgroundColor: color,
                          cursor: 'pointer',
                          border: selectedDanmuColor === color ? '2px solid #1890ff' : '2px solid #d9d9d9',
                          display: 'inline-block',
                          marginRight: 8,
                        }}
                        onClick={() => handleQuickColorSelect(color)}
                        title={color}
                      />
                    ))}
                  </Space>
                </div>
              </div>

              <Divider />

              <div style={{ marginBottom: 20 }}>
                <Typography.Title level={5}>{lang === 'zh' ? '时间控制' : 'Time Control'}</Typography.Title>
                <div style={{ marginBottom: 16 }}>
                  <span style={{ marginRight: 8 }}>{lang === 'zh' ? '时间偏移' : 'Time Offset'}</span>
                  <Slider 
                    min={-10} 
                    max={10} 
                    step={0.5} 
                    value={danmuTimeOffset} 
                    onChange={setDanmuTimeOffset} 
                    style={{ width: 200, display: 'inline-block' }} 
                  />
                  <span style={{ marginLeft: 8 }}>{danmuTimeOffset}s</span>
                </div>
                <div style={{ marginBottom: 16 }}>
                  <span style={{ marginRight: 8 }}>{lang === 'zh' ? '显示范围' : 'Display Range'}</span>
                  <Slider 
                    min={0.5} 
                    max={5} 
                    step={0.5} 
                    value={2} 
                    style={{ width: 200, display: 'inline-block' }} 
                    disabled
                  />
                  <span style={{ marginLeft: 8 }}>2s</span>
                </div>
              </div>

              <Divider />

              <div style={{ marginBottom: 20 }}>
                <Typography.Title level={5}>{lang === 'zh' ? '文字效果' : 'Text Effects'}</Typography.Title>
                <Space direction="vertical" style={{ width: '100%' }}>
                  <div>
                    <span style={{ marginRight: 8 }}>{lang === 'zh' ? '粗体' : 'Bold'}</span>
                    <Switch checked={danmuBold} onChange={setDanmuBold} />
                  </div>
                  <div>
                    <span style={{ marginRight: 8 }}>{lang === 'zh' ? '斜体' : 'Italic'}</span>
                    <Switch checked={danmuItalic} onChange={setDanmuItalic} />
                  </div>
                  <div>
                    <span style={{ marginRight: 8 }}>{lang === 'zh' ? '阴影效果' : 'Shadow Effect'}</span>
                    <Switch checked={danmuShadow} onChange={setDanmuShadow} />
                  </div>
                  <div>
                    <span style={{ marginRight: 8 }}>{lang === 'zh' ? '描边效果' : 'Stroke Effect'}</span>
                    <Switch checked={danmuStroke} onChange={setDanmuStroke} />
                  </div>
                </Space>
              </div>

              <div style={{ 
                padding: '12px', 
                background: '#f5f5f5', 
                borderRadius: '8px', 
                marginTop: '16px',
                textAlign: 'center'
              }}>
                <div style={{ 
                  color: selectedDanmuColor, 
                  fontSize: danmuFontSize, 
                  opacity: danmuOpacity,
                  fontWeight: danmuBold ? 'bold' : 'normal',
                  fontStyle: danmuItalic ? 'italic' : 'normal',
                  textShadow: danmuShadow ? `1px 1px 2px #000, 0 0 4px ${selectedDanmuColor}` : 'none',
                  WebkitTextStroke: danmuStroke ? '1px #000' : 'none',
                }}>
                  {lang === 'zh' ? '弹幕预览效果' : 'Danmu Preview'}
                </div>
              </div>
            </Modal>
          </div>
          {showChart && (
            <div className="chart" onClick={() => setShowChart(false)}
              style={{
                position: 'absolute',
                top: 0,
                left: 0,
                width: '100%',
                height: '100%',
                zIndex: 100,
                background: 'rgba(255,255,255,0.98)',
                display: 'flex',
                flexDirection: 'column',
                alignItems: 'center',
                justifyContent: 'center',
                cursor: 'pointer',
              }}
            >
              <div
                style={{
                  background: 'transparent',
                  display: 'flex',
                  flexDirection: 'column',
                  alignItems: 'center',
                  width: 320,
                  height: 400,
                  cursor: 'default',
                  boxShadow: '0 4px 24px rgba(0,0,0,0.12)',
                  borderRadius: 12,
                  padding: 16,
                }}
                onClick={e => e.stopPropagation()}
              >
                <div style={{ fontWeight: 600, marginBottom: 8, fontSize: 20 }}>AI 聊天</div>
                <div style={{
                  flex: 1,
                  minHeight: 60,
                  marginBottom: 8,
                  background: '#f5f5f5',
                  borderRadius: 8,
                  padding: 8,
                  width: '100%',
                  overflowY: 'auto',
                  maxHeight: 220,
                }}>
                  {chatMessages.map((msg, idx) => (
                    <div key={idx} style={{
                      textAlign: msg.from === 'user' ? 'right' : 'left',
                      margin: '6px 0',
                      display: 'flex',
                      justifyContent: msg.from === 'user' ? 'flex-end' : 'flex-start',
                    }}>
                      <span style={{
                        background: msg.from === 'user' ? '#3a8bff' : '#f0f0f0',
                        color: msg.from === 'user' ? '#fff' : '#333',
                        borderRadius: 12,
                        padding: '6px 12px',
                        fontSize: 15,
                        maxWidth: 200,
                        wordBreak: 'break-all',
                        display: 'inline-block',
                      }}>
                        {msg.text}
                      </span>
                    </div>
                  ))}
                  {chatLoading && <div style={{ color: '#888', fontSize: 12 }}>AI思考中...</div>}
                </div>
                <div style={{ display: 'flex', width: '100%' }}>
                  <input
                    style={{ borderRadius: 8, border: '1px solid #eee', padding: 8, width: '100%' }}
                    placeholder="请输入内容..."
                    value={chatInput}
                    onChange={e => setChatInput(e.target.value)}
                    onKeyDown={e => { if (e.key === 'Enter') sendChatMessage(); }}
                    disabled={chatLoading}
                  />
                  <button
                    style={{
                      marginLeft: 8,
                      borderRadius: 8,
                      border: 'none',
                      background: '#3a8bff',
                      color: '#fff',
                      padding: '0 16px',
                      cursor: 'pointer',
                      fontSize: 15,
                    }}
                    onClick={sendChatMessage}
                    disabled={chatLoading}
                  >发送</button>
                </div>
                <div style={{ color: '#aaa', marginTop: 8, fontSize: 12 }}>(点击空白处关闭)</div>
              </div>
            </div>
          )}
        </div>
        <div className="floor"></div>
      </div>
      {isAdmin && <ChatIcon onClick={() => setShowChart(v => !v)} />}
    </div>
  );
}

export default Index;
